/*
 * FileName：SouhuNewsViewJob.java 
 * <p>
 * Copyright (c) 2017-2020 <a href="https://www.smartwx.info">hermit(1154808491@qq.com)</a>.
 * <p>
 * Licensed under the GNU General Public License, Version 3 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/gpl-3.0.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package com.smart.webmagic.job;

import com.smart.common.util.HttpClientUtils;
import com.smart.wx.wxcms.entity.WxcmsNews;
import com.smart.wx.wxcms.service.WxcmsNewsService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Component
public class SouhuNewsViewJob implements Job,Serializable {

    @Resource
    private WxcmsNewsService wxcmsNewsService;

    /**
     * 获取阅读数
     */
    public static final String pvUrl="http://v2.sohu.com/public-api/articles/%s/pv";

    /**
     * 每天早晨4點更新
     *
     * @author hermit
     * @date 2017 -08-08 18:17:31
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try {
            List<WxcmsNews> wxcmsNewsList = wxcmsNewsService.queryList(new WxcmsNews());
            for (WxcmsNews wxcmsNews : wxcmsNewsList) {
                String view = HttpClientUtils.sendHttpGet(String.format(this.pvUrl, getNewsId(wxcmsNews.getNewsUrl())));
                wxcmsNews.setViewTotal(view);
                wxcmsNewsService.update(wxcmsNews);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取新闻id
     * @param msg
     * @return
     */
    public static String getNewsId(String msg){
        Pattern p = Pattern.compile("(/\\d{9}_)");
        Matcher m = p.matcher(msg);
        while(m.find()){
            return m.group().substring(1, m.group().length()-1);
        }
        return null;
    }
}
